package com.dk.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPath;
import com.dk.domain.ActionEntity;
import com.dk.domain.ApiAutoTestEntity;
import com.dk.domain.action.CaseActionBodyEntity;
import com.dk.domain.action.ExtractParameterEntity;
import com.dk.domain.action.GetVarEntity;
import com.dk.enumerate.DkRuleEnum;
import com.dk.exception.ExcelDataException;
import com.dk.testcase.BaseCase;
import com.dk.testflow.ApiAutoTestChainConfig;
import com.dk.util.String.StringUtil;
import com.dk.util.http.res.ResUtil;
import okhttp3.Headers;
import okhttp3.Response;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 执行测试用例
 */
public class ExcuteCaseHandler implements ActionStrategy{
    /**
     * 执行测试用例具体实现
     * @param actionEntity
     */
    @Override
    public void Action(ActionEntity actionEntity) throws ExcelDataException {
        //获取动作主体内容
        String actionBody = actionEntity.getActionBody();
        //获取需要提取的参数
        String extractParameter= actionEntity.getExtractParameter();
        //将动作主体内容转换为用例执行主体对象
        CaseActionBodyEntity caseActionBodyEntity = JSON.parseObject(actionBody, CaseActionBodyEntity.class);
        //根据用例编号执行测试用例获取测试对象
        ApiAutoTestEntity apiAutoTestEntity = ApiAutoTestChainConfig.getApiAutoTestChain().startExecute(BaseCase.apiAutoTestEntityMap.get(caseActionBodyEntity.getCaseNum()));
        //将提取参数内容转换为提取参数对象
        ExtractParameterEntity extractParameterEntity = JSON.parseObject(extractParameter, ExtractParameterEntity.class);
        //获取增加参数对象集合
        List<GetVarEntity> getVarList = extractParameterEntity.getGetVar();
        //遍历提取参数对象集合，获取需要的参数到公共参数集中
        getVarList.stream().forEach(getVar->{
            if(DkRuleEnum.HEADER.getValue().equals(getVar.getSub().toUpperCase())){//如果需要提取头部信息
                BaseCase.varEntityMap.put(getVar.getSetKey(), StringUtil.getValueInHeaders(apiAutoTestEntity.getResHeaders(),getVar.getGetValueInResult()));
            }else if(DkRuleEnum.BODY.getValue().equals(getVar.getSub().toUpperCase())){//如果需要提取响应体信息
                BaseCase.varEntityMap.put(getVar.getSetKey(),JSONPath.eval(apiAutoTestEntity.getResBody(),getVar.getGetValueInResult()));
            }else{
                try {
                    throw new ExcelDataException("---【error】:CaseAction-ExtractParameter提取参数格式错误:sub字段必须为枚举值header,body,错误ActionNum:"+actionEntity.getActionNum()+";");
                } catch (ExcelDataException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
